/*
 * LogFile.cc
 *
 *  Created on: 2021年4月5日
 *      Author: san
 */

#include "LogFile.h"

namespace san {

LogFile::LogFile(const std::string &basename, int flushEveryN)
	: basename_(basename),
	  flushEveryN_(flushEveryN),
	  count_(0),
	  mutex_(new MutexLock)
{
	file_.reset(new AppendFile(basename));
}

LogFile::~LogFile() {}

void LogFile::append(const char* logline, int len)
{
	// 先获取锁，再调用不锁定版本
	MutexLockGuard lock(*mutex_);
	append_unlock(logline, len);
}

void LogFile::flush()
{
	MutexLockGuard lock(*mutex_);
	file_->flush();
}

void LogFile::append_unlock(const char *logline, int len)
{
	file_->append(logline, len);
	++count_;

	// 如果长度大于 flushEveryN_, 则对缓冲区进行冲洗
	if (count_ >= flushEveryN_)
	{
		count_ = 0;
		file_->flush();
	}
}

} /* namespace san */
